<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="state.spuForm" :rules="state.rules" ref="spuRef" label-width="120px" class="spuForm">
        <el-form-item required label="商品分类">
          <el-select v-model="state.value" placeholder="请选择">
            <el-option
                v-for="item in state.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @change="state.categoryId = item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input style="width: 300px" v-model="state.spuForm.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品最低价格" prop="min_price">
          <el-input type="number" min="0" style="width: 300px" v-model="state.spuForm.min_price" placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="上架状态" prop="status">
          <el-radio-group v-model="state.spuForm.status">
            <el-radio label="1">上架</el-radio>
            <el-radio label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 添加文件上传组件 -->
        <el-form-item label="商品主图">
          <el-upload
              class="img-uploader"
              action="http://127.0.0.1:66/users/uploadImgs"
              method="post"
              :show-file-list="false"
              :on-success="handleUrlSuccess"
              :before-upload="handleBeforeUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="img">
            <i v-else class="el-icon-plus img-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品介绍">
          <div ref='editor'></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ state.id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer } from '@/utils'

const { proxy } = getCurrentInstance()
const editor = ref(null)
const spuRef = ref(null)
const route = useRoute()
const router = useRouter()
const { id } = route.query
const state = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  id: id,
  spuForm: {
    name: '',
    description: '',
    min_price: '',
    status: '1',
    image_url: '',
  },
  rules: {
    name: [
      { required: 'true', message: '请填写商品名称', trigger: ['change'] }
    ],
    min_price: [
      { required: 'true', message: '请填写商品价格', trigger: ['change'] }
    ]
  },
  options: [{
    value: '1',
    label: '悦健康'
  }, {
    value: '2',
    label: '李宁'
  }, {
    value: '3',
    label: '手表'
  }, {
    value: '4',
    label: '食品'
  }, {
    value: '6',
    label: '图书'
  }],
  value: ''
})
let instance
onMounted(() => {
  instance = new WangEditor(editor.value)
  instance.config.showLinkImg = false
  instance.config.showLinkImgAlt = false
  instance.config.showLinkImgHref = false
  instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
  instance.config.uploadFileName = 'file'
  instance.config.uploadImgHeaders = {
    token: state.token
  }
  // 图片返回格式不同，需要自定义返回格式
  instance.config.uploadImgHooks = {
    // 图片上传并返回了结果，想要自己把图片插入到编辑器中
    // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
    customInsert: function(insertImgFn, result) {
      console.log('result', result)
      // result 即服务端返回的接口
      // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
      if (result.data && result.data.length) {
        result.data.forEach(item => insertImgFn(item))
      }
    }
  }
  instance.config.uploadImgServer = uploadImgsServer
  Object.assign(instance.config, {
    onchange() {
      console.log('change')
    },
  })
  instance.create()
  if (id) {
    axios.get(`/spus/${id}`).then(res => {
      console.log(res)
      const spus = res;
      state.spuForm = {
        name: spus.name,
        description: spus.description,
        min_price: spus.min_price,
        status: String(spus.status),
        image_url: spus.image_url,
      }
      state.value= spus.category_name
      if (instance) {
        // 初始化商品详情 html
        instance.txt.html(spus.description)
      }
    })
  }
})
onBeforeUnmount(() => {
  instance.destroy()
  instance = null
})
const submitAdd = () => {
  spuRef.value.validate((vaild) => {
    if (vaild) {
      // 默认新增用 post 方法
      let httpOption = axios.post
      let params = {
        category_id: state.categoryId,
        image_url: state.spuForm.image_url,
        description: instance.txt.html(),
        name: state.spuForm.name,
        status: state.spuForm.status,
        min_price: state.spuForm.min_price,
      }
      console.log('params', params)
      if (id) {
        params.spu_id= id
        // 修改商品使用 put 方法
        httpOption = axios.put
      }
      httpOption('/spus', params).then(() => {
        ElMessage.success(id ? '修改成功' : '添加成功')
        router.push({ path: '/spus' })
      })
    }
  })
}
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || ''
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
    return false
  }
}
const imageUrl = ref('');
// 文件上传成功回调
const handleUrlSuccess = (res, file) => {
  console.log(res)
  imageUrl.value = URL.createObjectURL(file.raw);
};
</script>

<style scoped>
.add {
  display: flex;
}
.add-container {
  flex: 1;
  height: 100%;
}
.img-uploader .el-icon-plus {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.img-uploader .el-icon-plus:hover {
  border-color: #409EFF;
}

.img-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.img {
  width: 178px;
  height: 178px;
  display: block;
}</style>